package com.qch.concurrent.demo_01_semaphore;

import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * @Author qch
 * @Date 2021/8/2
 */
public class MyThread extends Thread {
    private final Semaphore semaphore;
    private final Random random = new Random();

    public MyThread(String name, Semaphore semaphore) {
        super(name);
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            //获取信标：抢座
            semaphore.acquire();
            //抢到之后开始写作业
            System.out.println(Thread.currentThread().getName()+"-抢到之后开始写作业");
            Thread.sleep(random.nextInt(1000));
            System.out.println(Thread.currentThread().getName()+"-作业写完腾出座位");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        semaphore.release();
    }
}
